﻿@using System.Web.Script.Serialization
@model BusinessLogic.DTO.CandidateDTO

@{
    ViewBag.Title = "AddCandidate";
    Layout = "~/Views/Shared/_adminLayout.cshtml";
}

<script type="text/javascript">
    var initialData = @Html.Raw(new JavaScriptSerializer().Serialize(Model));
    
    function UsersData(data) {
        this.UserId = ko.observable(data.UserId);
        this.Username = ko.observable(data.Username);
        this.Firstname = ko.observable(data.FirstName);
        this.Lastname = ko.observable(data.LastName);
    }
    
    function PositionData(data) {
        this.PositionId = ko.observable(data.PositionID);
        this.PositionName = ko.observable(data.PositionName);
    }

    var ViewModel = function() {
        var self = this;
        self.Users = ko.observableArray([]);
        self.AvailablePosition = ko.observableArray([]);
        self.Candidate = ko.observable();
        self.selectedUser = ko.observable();
        self.selectedPosition = ko.observable();

        self.validateForm = function() {
            var ErrorSpan = document.getElementById('errorSpan');
            
            if(ErrorSpan == null)
                return;

            if(self.AvailablePosition().length == 0)
                ErrorSpan.innerHTML = "Brak stanowisko dla tego użytkownika";
            else {
                ErrorSpan.innerHTML = "";
            }
        };

        self.loadData = function() {
            var mappedUsers = $.map(initialData.Users, function(item) { return new UsersData(item); });
            self.Users(mappedUsers);

            self.Candidate = ko.mapping.fromJS(initialData.Candidate);
        };
        
        self.positionChanged = function() {
            self.Candidate.PositionID = self.selectedPosition().PositionId();
            self.Candidate.UserId = self.selectedUser().UserId();
        };

        self.userChanged = function() {
            $.ajax("/Candidate/AvailablePositionsForUser", {
                data: ko.toJSON({ 
                    UserId: self.selectedUser().UserId()
                }),
                type: "post", contentType: "application/json",
                success: function(result) {  
                    var mappedPositions = $.map(result, function(item) { return new PositionData(item); });
                    self.AvailablePosition(mappedPositions);
                    self.validateForm();
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        };

        self.save = function() {

            self.validateForm();

            if(self.AvailablePosition().length == 0) {
                return;
            }

            $.ajax("/Candidate/Save", {
                data: ko.toJSON({ 
                    Candidate: self.Candidate
                }),
                type: "post", contentType: "application/json",
                success: function(result) { window.location.href = result; },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        }; 

    };

    var viewModel = new ViewModel();
    viewModel.loadData();
    
    $(document).ready(function () {
        ko.applyBindings(viewModel);
     });

</script>

<h2>Dodaj kandydata</h2>
 <form id="myform">
     
     <p>
         @Html.Label("Wybierz użytkownika:")
         <select data-bind="options: Users, optionsText: 'Username', value: selectedUser,event:{ change: userChanged}, optionsCaption: 'Wybierz...'"></select>   
     </p>

     <p>
         @Html.Label("Wybierz pozycje:")
         <select data-bind="options: AvailablePosition, optionsText: 'PositionName', value: selectedPosition, optionsCaption: 'Wybierz...', event:{ change: positionChanged}"></select>   
     </p>
     
      <span style="color: red" id="errorSpan"></span>

     <p>
         <button style="margin-top: 10px"data-bind="click: save">Dodaj kandydata</button>
     </p>
     
    
    
 </form>